package point

import (
	"encoding/json"
	"errors"
	"fmt"
	"kop/modules/configuration/client"
	"kop/util/log"
	"sort"
)

func init() {

	var err error
	var b = client.Load("TreasureAppraise")

	var m = make(map[int32]Conf)
	if err = json.Unmarshal(b, &m); err != nil {
		panic(err)
	}

	for _, v := range m {
		Configs = append(Configs, v)
	}

	sort.Sort(configs(Configs))

	log.Info("Load TreasureAppraise.json success.")

}

type Conf struct {
	Grade     int32   `json:"ID"` // 评价ID
	Score     int32   // 分数要求
	AwardRate float64 // 奖励加成
}

type configs []Conf

func (c configs) Len() int           { return len(c) }
func (c configs) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c configs) Less(i, j int) bool { return c[i].Score > c[j].Score }

var Configs []Conf

func GetByGrade(grade int32) (Conf, error) {

	for _, conf := range Configs {
		if grade == conf.Grade {
			return conf, nil
		}
	}

	return Conf{}, errors.New(fmt.Sprintf("Grade not found [%d]", grade))
}

func GetByPoint(point int32) (Conf, error) {

	for _, conf := range Configs {
		if point >= conf.Score {
			return conf, nil
		}
	}

	return Conf{}, errors.New(fmt.Sprintf("TreasurePoint not found [%d]", point))
}
